<!-- src/components/Login.vue -->
<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo-section">
        <div class="logo-icon">
          <i class="icon-graduation-cap"></i>
        </div>
        <h2>农民技能提升就业培训大数据平台</h2>
        <p>用户登录</p>
      </div>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <i class="icon-alert-circle"></i>
          {{ errorMessage }}
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-user"></i>
            用户名/邮箱/手机号
          </label>
          <input
            v-model="loginForm.username"
            type="text"
            required
            placeholder="请输入用户名、邮箱或手机号"
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-lock"></i>
            密码
          </label>
          <div class="password-input">
            <input
              v-model="loginForm.password"
              :type="showPassword ? 'text' : 'password'"
              required
              placeholder="请输入密码"
              :disabled="loading"
            />
            <button 
              type="button" 
              @click="showPassword = !showPassword"
              class="password-toggle"
              :disabled="loading"
            >
              <i :class="showPassword ? 'icon-eye-off' : 'icon-eye'"></i>
            </button>
          </div>
        </div>
        
        <div class="form-options">
          <label class="remember-me">
            <input type="checkbox" v-model="loginForm.rememberMe" />
            <span class="checkmark"></span>
            记住我
          </label>
          <router-link to="/forgot-password" class="forgot-password">
            忘记密码？
          </router-link>
        </div>
        
        <button type="submit" class="login-btn" :disabled="loading">
          <i v-if="loading" class="icon-loading"></i>
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      
      <div class="register-link">
        <p>还没有账户？ <router-link to="/register">立即注册</router-link></p>
      </div>
      
      <div class="login-footer">
        <p>© 2024 农民技能提升就业培训大数据平台</p>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-1"></div>
      <div class="decoration-2"></div>
      <div class="decoration-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const loading = ref(false)
const showPassword = ref(false)
const errorMessage = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// API 基础配置
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

// 登录API调用
const loginAPI = async (credentials) => {
  const response = await fetch(`${API_BASE_URL}/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(credentials)
  })
  
  if (!response.ok) {
    const errorData = await response.json()
    throw new Error(errorData.detail || '登录失败')
  }
  
  return await response.json()
}

// 处理登录
const handleLogin = async () => {
  errorMessage.value = ''
  loading.value = true
  
  try {
    const credentials = {
      username: loginForm.username.trim(),
      password: loginForm.password
    }
    
    const response = await loginAPI(credentials)
    
    // 存储token和用户信息
    authStore.setTokens({
      accessToken: response.access_token,
      refreshToken: response.refresh_token,
      expiresIn: response.expires_in
    })
    
    authStore.setUser(response.user_info)
    
    // 处理记住我功能
    if (loginForm.rememberMe) {
      localStorage.setItem('remember-user', loginForm.username)
    } else {
      localStorage.removeItem('remember-user')
    }
    
    // 登录后路由跳转逻辑
    await handlePostLoginRedirect()
    
  } catch (error) {
    console.error('登录失败:', error)
    errorMessage.value = error.message || '登录失败，请检查用户名和密码'
  } finally {
    loading.value = false
  }
}

// 登录后的路由跳转处理
const handlePostLoginRedirect = async () => {
  const userType = authStore.userType
  const isProfileCompleted = authStore.isProfileCompleted
  
  console.log('登录后路由判断:', {
    userType,
    isProfileCompleted,
    redirectQuery: route.query.redirect
  })
  
  // 如果用户信息不完整，跳转到信息完善页面
  if (!isProfileCompleted) {
    if (userType === 'student') {
      router.replace('/complete-profile/student')
    } else if (userType === 'teacher') {
      router.replace('/complete-profile/teacher')
    } else {
      // admin 用户直接跳转到管理后台
      router.replace(route.query.redirect || '/dashboard')
    }
    return
  }
  
  // 用户信息完整，根据类型跳转到相应的仪表盘
  let defaultRoute = '/dashboard'
  
  if (userType === 'teacher') {
    defaultRoute = '/teacher/dashboard'
  } else if (userType === 'student') {
    defaultRoute = '/student/dashboard'
  }
  
  // 如果有重定向参数，优先使用重定向地址
  const redirectTo = route.query.redirect || defaultRoute
  router.replace(redirectTo)
}

// 页面加载时恢复记住的用户名
onMounted(() => {
  // 从查询参数获取用户名（注册成功后跳转过来）
  if (route.query.username) {
    loginForm.username = route.query.username
  } else {
    // 否则尝试恢复记住的用户名
    const rememberedUser = localStorage.getItem('remember-user')
    if (rememberedUser) {
      loginForm.username = rememberedUser
      loginForm.rememberMe = true
    }
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.decoration-1,
.decoration-2,
.decoration-3 {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.decoration-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  right: 10%;
  animation: float 6s ease-in-out infinite;
}

.decoration-2 {
  width: 150px;
  height: 150px;
  bottom: 20%;
  left: 15%;
  animation: float 8s ease-in-out infinite reverse;
}

.decoration-3 {
  width: 100px;
  height: 100px;
  top: 60%;
  right: 20%;
  animation: float 10s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 420px;
  position: relative;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.logo-section h2 {
  margin: 0 0 8px 0;
  color: #1F2937;
  font-size: 20px;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 错误提示样式 */
.error-message {
  background: #FEF2F2;
  border: 1px solid #FECACA;
  color: #DC2626;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.error-message i {
  font-size: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group label i {
  color: #6B7280;
}

.form-group input {
  padding: 14px 16px;
  border: 2px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-group input:disabled {
  background-color: #F9FAFB;
  cursor: not-allowed;
}

.password-input {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6B7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.2s;
}

.password-toggle:hover:not(:disabled) {
  color: #374151;
}

.password-toggle:disabled {
  cursor: not-allowed;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #374151;
}

.remember-me input {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #D1D5DB;
  border-radius: 4px;
  position: relative;
  transition: all 0.2s;
}

.remember-me input:checked + .checkmark {
  background: #4F46E5;
  border-color: #4F46E5;
}

.remember-me input:checked + .checkmark::after {
  content: '✓';
  color: white;
  font-size: 12px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.forgot-password {
  color: #4F46E5;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.2s;
}

.forgot-password:hover {
  color: #4338CA;
}

.login-btn {
  padding: 14px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 注册链接样式 */
.register-link {
  text-align: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #E5E7EB;
}

.register-link p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.register-link a {
  color: #4F46E5;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
}

.register-link a:hover {
  color: #4338CA;
}

.login-footer {
  margin-top: 24px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #E5E7EB;
}

.login-footer p {
  margin: 0 0 12px 0;
  color: #6B7280;
  font-size: 12px;
}

.links {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.links a {
  color: #6B7280;
  text-decoration: none;
  font-size: 12px;
  transition: color 0.2s;
}

.links a:hover {
  color: #4F46E5;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 16px;
  }
  
  .login-box {
    padding: 32px 24px;
  }
  
  .logo-section h2 {
    font-size: 18px;
  }
  
  .form-options {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>